//对接相关设置在项目设置中展示
var curHost = window.location.host;

if(curHost.indexOf('www.fsyuncai') != -1){
    var orderSetIdArr = ['GJP0000001','D000000033']; //管家婆和无人仓
}else{
    var orderSetIdArr = ['GJP0000001','UW00000001'];
}



var no = 0;
function upLoadFile() {
    $("#fileUp").trigger('click');
}
function putDataToPage() {
    /*渲染spu sku值到页面*/
    var formData = new FormData();
    formData.append('file', $("#fileUp")[0].files[0]);
    // console.log($("#fileUp")[0].value)
    $.ajax({
        url: root.dockingplatform.importSubChannelConfigInfo,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data)
            if(data.errorCode==0){
                $.Huimodalalert("导入成功",2000);
                setTimeout(function () {
                    location.replace(location.href);
                }, 1000);
            }else {
                $.Huimodalalert(data.msg,2000);
                setTimeout(function () {
                    location.replace(location.href);
                }, 1000);
            }

        }
    });
}



//下载
//$('#downloadProductExcelTemplate').attr('href','https://'+ window.location.host +'/baseservice/downLoadFromUrl?urlStr= https://fsyuncai-file.oss-cn-beijing.aliyuncs.com/common/20190614163005280641.xlsx&fileName=价格设置-导入商品模板')
$('#exportSubChannelConfigInfo').attr('href',root.dockingplatform.exportSubChannelConfigInfo);
function downloadTem() {
    $.ajax({
        url: root.dockingplatform.exportSubChannelConfigInfo,
        cache: false,  //禁用缓存
        type: "GET",
        data: "",
        success: function (data) {
            console.log(data);
        }
    });
}
function sku_cha() {
    $('#create-status').remove();
    console.log("costmerCode===",sessionStorage.getItem("customerCode"));
    if(sessionStorage.getItem("customerCode") == 'D000000028' || sessionStorage.getItem("customerCode") == 'D000000031' || sessionStorage.getItem("customerCode") == 'D000000030' || sessionStorage.getItem("customerCode") == 'D000000034'|| sessionStorage.getItem("customerCode") == 'D000000035'|| sessionStorage.getItem("customerCode") == 'D000000041'|| sessionStorage.getItem("customerCode") == 'D000000034'|| sessionStorage.getItem("customerCode") == 'D000000033'|| sessionStorage.getItem("customerCode") == 'D000000040') {
        $('#custom').after('<th width="50" id="create-status">创建状态</th>');
    } else {
        $('#create-status').remove();
    }
    $.ajax({
        contentType: 'application/json',
        //url: root.goodsInter.goods_getSkuList,
        url: root.dockingplatform.listSubChannelConfigByParentCustomerCode,
        cache: false,  //禁用缓存
        type: "POST",
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":2000,
            "parentCustomerCode":sessionStorage.getItem("customerCode"),
            //"parentCustomerCode":"11.11.111111",
            //"customerName":sessionStorage.getItem("customerName")
        }),
        success: function (data) {
            //sessionStorage.setItem("CRMCode",data.data.result.parentCustomerCode);
            console.log(data)
            skuList(data);
            $("#spu_all").attr("checked",false);
            totalPage = data.data.totalPage;
            $('.M-box4').pagination({
                pageCount: totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function(api) {
                    console.log(api.getCurrent());
                    $.ajax({
                        contentType: 'application/json',
                        //url: root.goodsInter.goods_getSkuList,
                        url: root.dockingplatform.queryChannelSkuList,
                        cache: false,  //禁用缓存
                        type: "POST",
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":2000,
                            "parentCustomerCode":sessionStorage.getItem("customerCode"),
                            //"parentCustomerCode":"11.11.111111",
                        }),
                        success: function (data) {
                            skuList(data);
                            $("#spu_all").attr("checked",false);
                        }
                    });
                }
            });
        }
    });
    /*}*/

}



var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];

function skuList(data) {
    dataSource.splice(0, dataSource.length);//清空数组
    $.each(data.data.result, function (i, field) {
        // if(field.status == 0) return true; // 如果status为0，就表示删除，不显示这一行数据
        if((sessionStorage.getItem("customerCode") == 'D000000028' || sessionStorage.getItem("customerCode") == 'D000000031' || sessionStorage.getItem("customerCode") == 'D000000030' || sessionStorage.getItem("customerCode") == 'D000000034'|| sessionStorage.getItem("customerCode") == 'D000000035'|| sessionStorage.getItem("customerCode") == 'D000000041'|| sessionStorage.getItem("customerCode") == 'D000000034'|| sessionStorage.getItem("customerCode") == 'D000000033'|| sessionStorage.getItem("customerCode") == 'D000000040') && field.status == 0) return true;
        var rowData = new Array();
        rowData.push(field.customerId); //我司客户id 0
        rowData.push(field.customerCode); //客户代码 1
        rowData.push(field.customerName); //客户名称2
        rowData.push(field.projectId);  //项目编码3
        rowData.push(field.projectName);  //项目名称4
        rowData.push(field.belongGroupName ); //客户所属名称 5
        rowData.push(field.id);  //主键id 6
        rowData.push(field.parentCustomerCode); //渠道code 7
        rowData.push(field.receiverCompanyName); //收货公司名称 8
        rowData.push(field.invoiceCompanyName); //开票公司名称 9
        rowData.push(field.projectBelongName);  //对方所属分公司 10
        rowData.push(field.mainCustomers);  //是否开启主客户 11 
        rowData.push(no);  //是否有主客户 12 
        rowData.push(field.status); // 是否创建 13
        if(field.isMainCustomers){
            no = 1;
        }
        rowData.push(field.contacts);
        rowData.push(field.telephone);
        rowData.push(field.address);
        dataSource.push(rowData);
    });
    initDataTable(dataSource);

    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        var targetsId = 9;
        var columnDefs = [];
        if(sessionStorage.getItem("customerCode") == 'D000000028' || sessionStorage.getItem("customerCode") == 'D000000031' || sessionStorage.getItem("customerCode") == 'D000000030' || sessionStorage.getItem("customerCode") == 'D000000034' || sessionStorage.getItem("customerCode") == 'D000000035'|| sessionStorage.getItem("customerCode") == 'D000000041'|| sessionStorage.getItem("customerCode") == 'D000000034'|| sessionStorage.getItem("customerCode") == 'D000000033'|| sessionStorage.getItem("customerCode") == 'D000000040') {
            targetsId = 10;
            columnDefs.push({
                /* 是否已创建 */
                "render": function (data, type, row, meta) {
                    // console.log(row);
                    var isCreate = '';
                    if(row[13] == 1) {
                        isCreate = '未创建';
                    } else if(row[13] == 2) {
                        isCreate = '已创建';
                    }
                    var val = '<span>' + isCreate + '</span>';
                    return val;
                },
                "targets": 9
            });
            $('#status-select').show();
            $('.looking-btn').css('visibility', 'visibile');
        }else {
            $('#status-select').hide();
            $('.looking-btn').css('visibility', 'hidden');
        }
        columnDefs.push(
            {
                "sTitle": "序号",
                "sClass": "dt-center",
                "bSortable": false,
                "sWidth": "4%",
                "data": null,
                "targets": 0
            },
            {
                /*渠道*/
                "render": function (data, type, row, meta) {
                    //var val = '<span><input class="skuId" type="checkbox" name="skuId" value = "'+ row[7] +'">Code码：'+row[8]+'</span>';
                    var val = '<span>' + sessionStorage.getItem("customerName") + '</span>';
                    return val;
                },
                "targets": 1
            },
            {
                /*我司客户ID*/
                "render": function (data, type, row, meta) {
                    if (row[0] == null) {
                        row[0] = '';
                    }
                    // if (row[12] == null){
                    //     row[12] = '';
                    // }
                    /*var val = '<span>批发价：'+row[2]+'</span><br><span>零售价：'+row[9]+'</span>';*/
                    //var val = '<span>' +row[12]+ '&nbsp' +row[11]+ ' </span>';
                    var val = '<span>' + row[0] + ' </span>';
                    return val;
                },
                "targets": 2
            },

            {
                /*CRM代码*/
                "render": function (data, type, row, meta) {
                    if (row[1] == null) {
                        row[1] = '';
                    }
                        var val = '<span>' + row[1] + '</span>';
                        return val;
                    },
                "targets": 3
            },
            {
                /*客户名称*/
                "render": function (data, type, row, meta) {
                    if (row[2] == null) {
                        row[2] = '';
                    }
                    var val = '<span>' + row[2] + '</span>';
                    return val;
                },
                "targets": 4
            },
            {
                /*对方项目编码*/
                "render": function (data, type, row, meta) {
                    if (row[3] == null) {
                        row[3] = '';
                    }

                    var val = '<span>' + row[3] + '</span>';
                    return val;
                },
                "targets": 5
            },
            {
                /*对方项目名称*/
                "render": function (data, type, row, meta) {
                    /*if (row[4] == null) {
                        row[4] = '';
                    }*/
                    var val = '<span>' + row[4] + '</span>';
                    return val;
                },


                "targets": 6
            },
            {
                /*对方所属子公司*/
                "render": function (data, type, row, meta) {
                    if (row[5] == null) {
                        row[5] = '';
                    }
                    var val = '<span>' + row[10] + '</span>';
                    return val;
                },


                "targets": 7
            },
            {
                /*是否是主客户*/
                "render": function (data, type, row, meta) {
                    var val = row[11]
                    if (val == 1) {
                        val = '是'
                    }else {
                        val = '否'
                    }
                    return val;
                },
                "targets": 8
            },
            {
                /*推送时间*/
                "render": function (data, type, row, meta) {
                    var aaa=row[4].replace("\n","");
                    if(orderSetIdArr.indexOf(row[7]) != -1){
                        var orderSetting = '<a onclick="subChannelDetails(\'订单相关设置\',\'xdgl_sub_ddxgsz.html\',\''+row[1]+'\',\''+row[6]+'\',\''+row[2]+'\')">订单相关设置</a><br>';
                        return '<span class="">'+orderSetting+'<a onclick="editProject(\'新增项目\',\'addProject.html\',\'' + row[0] + '\',\'' + row[1] + '\',\'' + row[2] + '\',\'' + row[3] + '\',\'' + aaa+ '\',\'' + row[5] + '\',\'' + row[6] + '\',\'' + row[7] + '\',\'' + row[8] + '\',\'' + row[9] + '\',\'' + row[10] + '\',\'' + row[11] + '\',\'' + row[12] + '\',\'' + row[13] + '\',\'' + row[14] + '\',\'' + row[15] + '\',\'' + row[16] + '\')">编辑</a></span><span>&nbsp&nbsp<a onclick="detaildelete(\'' + row[6] + '\',\'' + row[1] + '\')">删除</a></span>';
                    }
                    var val = '<span class=""><a onclick="editProject(\'新增项目\',\'addProject.html\',\'' + row[0] + '\',\'' + row[1] + '\',\'' + row[2] + '\',\'' + row[3] + '\',\'' + aaa+ '\',\'' + row[5] + '\',\'' + row[6] + '\',\'' + row[7] + '\',\'' + row[8] + '\',\'' + row[9] + '\',\'' + row[10] + '\',\'' + row[11] + '\',\'' + row[12] + '\',\'' + row[13] + '\',\'' + row[14] + '\',\'' + row[15] + '\',\'' + row[16] + '\')">编辑</a></span><span>&nbsp&nbsp<a onclick="detaildelete(\'' + row[6] + '\',\'' + row[1] + '\')">删除</a></span>';
                    return val;
                },
                "targets": targetsId
            },
        );
        $("#datatable").DataTable({
            "order": [[1, "esc"]],
            "autoWidth": false,
            "ordering": true,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [5, 10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            "fnDrawCallback": function () {
                this.api().column(0).nodes().each(function (cell, i) {
                    cell.innerHTML = i + 1;
                });
            },
            data: dataSource,
            columnDefs: columnDefs
           /* "fnInitComplete": function (oSettings, json) {
                setBtnDis(0, $("#productSkuManage"));
                $("#datatable").on("click", '.skuId', function () {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productSkuManage"));
                });

            }*/
        });
        //权限控制函数
        // power()

    }

}

//价格设置
function subChannelDetails(title,url,data,ids,name){
    sessionStorage.removeItem("click_a")
    sessionStorage.removeItem("click_b")
    sessionStorage.removeItem("zhekoulv")
    sessionStorage.setItem("customerName",name);
    sessionStorage.setItem("id",ids);
    sessionStorage.setItem("customerid",data);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

function editProject(title,url,customerId,customerCode,customerName,projectId,projectName,belongGroupName,id,parentCustomerCode,receiverCompanyName,invoiceCompanyName,projectBelongName,mainCustomers,isNo,isCreateStatus,contacts,telephone,address) {
    /*rowData.push(field.customerId); //我司客户id
    rowData.push(field.customerCode); //客户代码
    rowData.push(field.customerName); //客户名称
    rowData.push(field.projectId);  //项目编码
    rowData.push(field.projectName);  //项目名称
    rowData.push(field.belongGroupName ); //客户所属名称
    rowData.push(field.id);  //主键id
    rowData.push(field.parentCustomerCode); //渠道code
    rowData.push(field.receiverCompanyName); //收货公司名称
    rowData.push(field.invoiceCompanyName); //开票公司名称
    rowData.push(field.projectBelongName);  //对方所属分公司*/

/*    if(parentCustomerCode == "DJ00000007"){
        url="addZjProject.html"
    }*/



    var editdata={
        "customerId":customerId, //我司客户id
        "customerCode":customerCode, //客户代码
        "customerName":customerName, //客户名称
        "projectId":projectId, //项目编码
        "projectName":projectName, //项目名称
        "belongGroupName":belongGroupName,  //客户归属
        "receiverCompanyName":receiverCompanyName,//收货公司名称
        "invoiceCompanyName":invoiceCompanyName,//开票公司名称
        "projectBelongName":projectBelongName,//所属分公司
        "mainCustomers":mainCustomers,//所属分公司
        "isCreateStatus":isCreateStatus,//是否创建状态
        "contacts":contacts,//联系人
        "telephone":telephone,//手机号
        "address":address//地址
    };
    sessionStorage.setItem("isNo",parseInt(isNo));
    sessionStorage.setItem("id",parseInt(id));
    console.log(sessionStorage.getItem("id"));
    console.log(sessionStorage.getItem("isNo"));
    sessionStorage.setItem("editdata",JSON.stringify(editdata));
    sessionStorage.setItem("customerCode",parentCustomerCode);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}



function addProject(title,url) {
    //sessionStorage.setItem("customerCode");
    /*sessionStorage.removeItem("customerId");
    sessionStorage.removeItem("customerName");
    sessionStorage.removeItem("customerCode");*/

    console.log(sessionStorage.getItem("customerCode"));
    sessionStorage.removeItem("id");
    var index = layer.open({
        type: 2,
        title: title,
        content: url,
        end:function () {
            location.reload();
        }
    });
    layer.full(index);
}
function detaildelete(id,customerCode){
    web.doAjax(root.approvedServiceProviders.findProviderCooperationByCustomerNumberList, 'post', [customerCode], function (data) {
        if(data.code == 0){
            console.log(data)
            if(data.data.length==0){
                layer.confirm('确认删除该项目？',function () {
                    $.ajax({
                        contentType: 'application/x-www-form-urlencoded',
                        url: root.dockingplatform.deleteSubChannelConfigInfo,
                        cache: false,  //禁用缓存
                        type: "POST",
                        data: {id:id},
                        success: function (data) {
                            if(data.errorCode==0){
                                layer.msg("删除成功", {icon: 1, time: 2000});
                                sku_cha();
                            }else {
                                layer.msg("删除失败", {icon: 1, time: 2000});
                            }
                        }
                    });
                })
            }else {
                $.Huimodalalert("该客户存在关联关系，不能删除",2000);
            }
        }else {
            $.Huimodalalert(data.msg,2000);
        }
    },1);
}

$('.looking-btn').click(function (e) {
    console.log($('#status-select option:selected').val());
    renderStatusSelect();
})

function renderStatusSelect() {
    // console.log('9888')
    console.log(sessionStorage.getItem("customerCode"))
    if(sessionStorage.getItem("customerCode") == 'D000000028' || sessionStorage.getItem("customerCode") == 'D000000031' || sessionStorage.getItem("customerCode") == 'D000000030' || sessionStorage.getItem("customerCode") == 'D000000034'|| sessionStorage.getItem("customerCode") == 'D000000035'|| sessionStorage.getItem("customerCode") == 'D000000041'|| sessionStorage.getItem("customerCode") == 'D000000034'|| sessionStorage.getItem("customerCode") == 'D000000033'|| sessionStorage.getItem("customerCode") == 'D000000040') {
        // console.log($('#status-select option:selected').val());
        var status = $('#status-select option:selected').val();
        // status == 0 ? status == null : status;
        status = Number(status)
        status == 0 ? status = null : status;
        $.ajax({
            contentType: 'application/json',
            //url: root.goodsInter.goods_getSkuList,
            url: root.dockingplatform.listSubChannelConfigByParentCustomerCode,
            cache: false,  //禁用缓存
            type: "POST",
            data: JSON.stringify({
                "pageNum":1,
                "pageSize":2000,
                "parentCustomerCode":sessionStorage.getItem("customerCode"),
                "status": status
                //"parentCustomerCode":"11.11.111111",
                //"customerName":sessionStorage.getItem("customerName")
            }),
            success: function (data) {
                //sessionStorage.setItem("CRMCode",data.data.result.parentCustomerCode);
                console.log(data)
                skuList(data);
                $("#spu_all").attr("checked",false);
                totalPage = data.data.totalPage;
                $('.M-box4').pagination({
                    pageCount: totalPage,
                    jump: true,
                    coping: true,
                    prevContent: '上页',
                    nextContent: '下页',
                    callback: function(api) {
                        console.log(api.getCurrent());
                        $.ajax({
                            contentType: 'application/json',
                            //url: root.goodsInter.goods_getSkuList,
                            url: root.dockingplatform.queryChannelSkuList,
                            cache: false,  //禁用缓存
                            type: "POST",
                            data: JSON.stringify({
                                "pageNum":api.getCurrent(),
                                "pageSize":2000,
                                "parentCustomerCode":sessionStorage.getItem("customerCode"),
                                //"parentCustomerCode":"11.11.111111",
                            }),
                            success: function (data) {
                                skuList(data);
                                $("#spu_all").attr("checked",false);
                            }
                        });
                    }
                });
            }
        });
    } else return 
}

